#!/usr/bin/env python
# import sip
# sip.setapi('QVariant', 2)

from PySide.QtCore import *
from PySide.QtGui import *

import datahandler
import commonfunctions

class CreateTableTab(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.data = datahandler.DataHandler()
        self.common = commonfunctions.CommonFunctions()
        self.parent = parent
        self.addtableAction = QAction(QIcon(QDir.currentPath() + "/images/list-add.png"), "Add Table", self)
        self.deltableAction = QAction(QIcon(QDir.currentPath() + "/images/list-remove.png"), "Remove Selected Table", self)
        self.addrowAction = QAction(QIcon(QDir.currentPath() + "/images/row-add"), "Insert Row", self)
        self.delrowAction = QAction(QIcon(QDir.currentPath() + "/images/row-del.png"), "Delete Row", self)
        self.addcolAction = QAction(QIcon(QDir.currentPath() + "/images/col-add.png"), "Insert Column", self)
        self.delcolAction = QAction(QIcon(QDir.currentPath() + "/images/col-del.png"), "Delete Column", self)
        self.propertyAction = QAction(QIcon(QDir.currentPath() + "/images/document-properties.png"), "Edit Table Caption", self)
        self.updatetableAction = QAction(QIcon(QDir.currentPath() + "/images/document-save.png"), "Update Table Content", self)

        self.tabletb = QToolBar()
        self.tabletb.addAction(self.addtableAction)
        self.tabletb.addAction(self.deltableAction)
        self.tabletb.addSeparator()
        self.tabletb.addAction(self.addrowAction)
        self.tabletb.addAction(self.delrowAction)
        self.tabletb.addAction(self.addcolAction)
        self.tabletb.addAction(self.delcolAction)
        self.tabletb.addSeparator()
        self.tabletb.addAction(self.propertyAction)
        self.tabletb.addAction(self.updatetableAction)
        self.tabletb.setStyleSheet("QToolBar { border: 0px }")

        self.deltableAction.setEnabled(False)
        self.addrowAction.setEnabled(False)
        self.delrowAction.setEnabled(False)
        self.addcolAction.setEnabled(False)
        self.delcolAction.setEnabled(False)
        self.propertyAction.setEnabled(False)
        self.updatetableAction.setEnabled(False)
 
        self.tableList = QListWidget()
        self.tableList.setMaximumWidth(150)
        self.tableList.setSelectionMode(QAbstractItemView.SingleSelection)
        self.tableList.setAlternatingRowColors(True)
        self.tableList.setFrameStyle(QFrame.Panel)
        self.tableEditor = QTableWidget()
        self.tableEditor.setFrameStyle(QFrame.Panel)
        self.mainBox = QVBoxLayout()
        self.topBox = QHBoxLayout()
        self.botBox = QHBoxLayout()
        self.topBox.addWidget(self.tabletb)
        self.botBox.addWidget(self.tableList)
        self.botBox.addWidget(self.tableEditor)
        self.mainBox.addLayout(self.topBox)
        self.mainBox.addLayout(self.botBox)
        self.setLayout(self.mainBox)
        # connect actions
        self.addtableAction.triggered.connect(self.addTable)
        self.propertyAction.triggered.connect(self.editCaption)
        self.addrowAction.triggered.connect(self.addRow)
        self.delrowAction.triggered.connect(self.delRow)
        self.addcolAction.triggered.connect(self.addCol)
        self.delcolAction.triggered.connect(self.delCol)
        self.tableList.itemSelectionChanged.connect(self.showTable)
        self.deltableAction.triggered.connect(self.delTable)
        self.updatetableAction.triggered.connect(self.updateTable)
 
    def addTable(self):
        tmptablecaption, ok = QInputDialog.getText(self, "Table Caption", "Create the Table Caption:")
        if ok and tmptablecaption:
            self.data.sql(self.data.insertTable, [tmptablecaption, self.parent.currentcaseid], 0)
            self.updateTableList()
            
    def delTable(self):
        self.checkMessage = QMessageBox.warning(self, "Delete Table", "Are you sure you want to delete the table?\n This action cannot be undone.", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if self.checkMessage is QMessageBox.StandardButton.Yes:
            self.data.sql(self.data.deleteTable, [self.parent.currenttableid], 0)
            self.updateTableList()

    def editCaption(self):
        tmptablecaption, ok = QInputDialog.getText(self, "Table Caption", "Modify the Table Caption:")
        if ok and tmptablecaption:
            self.data.sql(self.data.updateTableCaption, [self.parent.currenttableid, tmptablecaption], 0)
            self.updateTableList()

    def addRow(self):
        self.tableEditor.insertRow(self.tableEditor.currentRow())

    def delRow(self):
        self.tableEditor.removeRow(self.tableEditor.currentRow())

    def addCol(self):
        self.tableEditor.insertColumn(self.tableEditor.currentColumn())

    def delCol(self):
        self.tableEditor.removeColumn(self.tableEditor.currentColumn())

    def updateTable(self):
        tmpdata = ""
        for i in range(0, self.tableEditor.rowCount()):
            if(i > 0): tmpdata += "||"
            for j in range(0, self.tableEditor.columnCount()):
                if(j > 0 and j < self.tableEditor.columnCount()): tmpdata += "::"
                if self.tableEditor.item(i, j) is not None:
                    tmpdata += self.tableEditor.item(i, j).text()
                else:
                    tmpdata += ""
        self.data.sql(self.data.updateTableData, [tmpdata, self.parent.currenttableid], 0)
        self.updateTableList()

    def updateTableList(self):
        self.tableList.clear()
        self.tableList.addItems(self.data.sql(self.data.updateTableList, [self.parent.currentcaseid], 1))
        for tmpaction in [self.deltableAction, self.addrowAction, self.delrowAction, self.addcolAction, self.delcolAction, self.propertyAction, self.updatetableAction]:
            if tmpaction.isEnabled() is True:
                tmpaction.setEnabled(False)
        self.tableEditor.clear()
        self.tableEditor.setRowCount(0)
        self.tableEditor.setColumnCount(0)

    def showTable(self):
        if self.tableList.count() > 0:
            self.tableEditor.clear()
            self.tableEditor.setRowCount(0)
            self.tableEditor.setColumnCount(0)
            for tmpaction in [self.deltableAction, self.addrowAction, self.delrowAction, self.addcolAction, self.delcolAction, self.propertyAction, self.updatetableAction]:
                if tmpaction.isEnabled() is False:
                    tmpaction.setEnabled(True)
            self.currenttabledata, self.parent.currenttableid = self.data.sql(self.data.getTableValuesFromTableList, [self.tableList.currentItem().text(), self.parent.currentcaseid], 1)
            if len(self.currenttabledata) > 0:
                self.tableEditor.setRowCount(len(self.currenttabledata))
                self.tableEditor.setColumnCount(len(self.currenttabledata[0]))
                for i in range(0, len(self.currenttabledata)):
                    for j in range(0, len(self.currenttabledata[i])):
                        self.tableEditor.setItem(i, j, QTableWidgetItem(self.currenttabledata[i][j]))
